﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;

namespace System.Web.Helpers
{
    public static class rusisGridNavigationHelper
    {
        public static MvcHtmlString rsGridNavigation(this HtmlHelper helper, int currentPage, int pageCount, RouteValueDictionary currentRouteValues)
        {
            string rsGridNavigationCSS = "rsGridNavigation";
            string rsBeginLinkCSS = "rsBeginLink";
            string rsPrevLinkCSS = "rsPrevLink";
            string rsPageNumCSS = "rsPageNum";
            string rsPageCountCSS = "rsPageCount";
            string rsNextLinkCSS = "rsNextLink";
            string rsEndLinkCSS = "rsEndLink";
            string rsItemsPerPageCSS = "rsItemsPerPage";
            string rsGridNavigationPageCSS = "rsGridNavigationPage";

            var urlHelper = new UrlHelper(helper.ViewContext.Controller.ControllerContext.RequestContext);

            StringBuilder builder = new StringBuilder();

            int currentStart = (int)currentRouteValues["start"];
            int itemsPerPage = (int)currentRouteValues["itemsPerPage"];

            builder.AppendLine("    <div class='" + rsGridNavigationCSS + "'>");
            builder.AppendLine("    <div class='" + rsGridNavigationPageCSS + "'>");
            if (currentPage != 1)
            {
                currentRouteValues["start"] = 0;
                builder.AppendLine("            <a href=\"" + urlHelper.RouteUrl(currentRouteValues) + "\" class=\"" + rsBeginLinkCSS + "\">|&lt;</a>");
                currentRouteValues["start"] = currentStart - itemsPerPage;
                builder.AppendLine("            &nbsp;&nbsp;<a href=\"" + urlHelper.RouteUrl(currentRouteValues) + "\" class=\"" + rsPrevLinkCSS + "\">&lt;&lt;</a>");
            }
            else
            {
                builder.AppendLine("            <span class=\"" + rsBeginLinkCSS + "\">|&lt;</span>&nbsp;&nbsp;<span class=\"" + rsPrevLinkCSS + "\">&lt;&lt;</span>");
            }

            builder.AppendLine("        &nbsp;&nbsp;<span>Страница</span>&nbsp;<span class=\"" + rsPageNumCSS + "\">" + currentPage.ToString() + "</span>&nbsp;<span>из</span>&nbsp;<span class=\"" + rsPageCountCSS + "\">" + pageCount.ToString() + "</span>&nbsp;&nbsp;");
            if (currentPage != pageCount)
            {
                currentRouteValues["start"] = currentStart + itemsPerPage;
                builder.AppendLine("            <a href=\"" + urlHelper.RouteUrl(currentRouteValues) + "\" class=\"" + rsNextLinkCSS + "\">&gt;&gt;</a>");
                currentRouteValues["start"] = (pageCount - 1) * itemsPerPage;
                builder.AppendLine("            &nbsp;&nbsp;<a href=\"" + urlHelper.RouteUrl(currentRouteValues) + "\" class=\"" + rsEndLinkCSS + "\">&gt;|</a>");
            }
            else
            {
                builder.AppendLine("            <span class=\"" + rsNextLinkCSS + "\">&gt;&gt;</span>&nbsp;&nbsp;<span class=\"" + rsEndLinkCSS + "\">&gt;|</span>");
            }
            builder.AppendLine("    </div>");

            currentRouteValues["start"] = currentStart;
            builder.AppendLine("    <div class=\"" + rsItemsPerPageCSS + "\">");
            builder.AppendLine("        Строк на странице:");
            builder.AppendLine("            <select id=\"itemsPerPage\" name=\"itemsPerPage\" onChange='redirectWidthNewPageSize(\"" + urlHelper.RouteUrl(currentRouteValues) + "\", this)'>");
            builder.AppendLine("                <option value=\"10\"" + ((10 == (int)currentRouteValues["itemsPerPage"]) ? " selected " : "") + ">10</option>");
            builder.AppendLine("                <option value=\"20\"" + ((20 == (int)currentRouteValues["itemsPerPage"]) ? " selected " : "") + ">20</option>");
            builder.AppendLine("                <option value=\"50\"" + ((50 == (int)currentRouteValues["itemsPerPage"]) ? " selected " : "") + ">50</option>");
            builder.AppendLine("                <option value=\"100\"" + ((100 == (int)currentRouteValues["itemsPerPage"]) ? " selected " : "") + ">100</option>");
            builder.AppendLine("            </select>");
            builder.AppendLine("    </div>");
            builder.AppendLine("    <script>");
            builder.AppendLine("        function redirectWidthNewPageSize(currentRouteValues, select) {");
            builder.AppendLine("            selectedValue = select.options[select.selectedIndex].value; // Выбранное значение количества строк грида на экране");
            builder.AppendLine("	        var tmp = new Array();      // два вспомагательных");
            builder.AppendLine("	        var tmp2 = new Array();     // массива");
            builder.AppendLine("	        var param = new Array();");
            builder.AppendLine("	        newUrl = \"\";");
            builder.AppendLine("	        tmp = (currentRouteValues.substr(0)).split('&');   // разделяем переменные");
            builder.AppendLine("	        for(var i=0; i < tmp.length; i++)");
            builder.AppendLine("	        {");
            builder.AppendLine("	            tmp2 = tmp[i].split('=');       // массив param будет содержать");
            builder.AppendLine("	            if (tmp2[0] == \"itemsPerPage\")");
            builder.AppendLine("	                tmp2[1] = selectedValue; // Если нашелся параметр itemsPerPage, то присваиваем новое значение");
            builder.AppendLine("                param[tmp2[0]] = tmp2[1];       // пары ключ(имя переменной)->значение");
            builder.AppendLine("	        }");
            builder.AppendLine("            // Формирование нового Url с измененным параметром itemsPerPage");
            builder.AppendLine("	        for (var key in param)");
            builder.AppendLine("	        {");
            builder.AppendLine("	            newUrl = newUrl + key + \"=\" + param[key] + \"&\";");
            builder.AppendLine("	        }");
            builder.AppendLine("	        newUrl = newUrl.substr(0, (newUrl.length-1));");
            builder.AppendLine("	        window.location = newUrl;");
            builder.AppendLine("        }");
            builder.AppendLine("    </script>");

            return new MvcHtmlString(builder.ToString());
        }

    }
}
